import React, { useState, useEffect } from 'react';
import { Form, Input, Select, DatePicker, Button, Table, Tag, Modal, message, Tree } from 'antd';
import { PlusOutlined, SettingOutlined } from '@ant-design/icons';
import { BugItem, BugQueryParams } from '@/g-types/bug';
import { bugServer } from './server';
import './index.less';
import type { Key } from 'rc-tree/lib/interface';

const { RangePicker } = DatePicker;
const { Option } = Select;

export const BugList: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<BugItem[]>([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [visible, setVisible] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingBug, setEditingBug] = useState<BugItem | null>(null);
  const [searchFields, setSearchFields] = useState<string[]>(['title', 'status', 'priority', 'reporter', 'createTime']);

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag className="status-tag" color={
          status === 'pending' ? 'orange' :
          status === 'processing' ? 'blue' :
          'green'
        }>
          {status === 'pending' ? '待处理' :
           status === 'processing' ? '处理中' :
           '已解决'}
        </Tag>
      ),
    },
    {
      title: '优先级',
      dataIndex: 'priority',
      key: 'priority',
      render: (priority: string) => (
        <Tag className="priority-tag" color={
          priority === 'high' ? 'red' :
          priority === 'medium' ? 'orange' :
          'green'
        }>
          {priority === 'high' ? '高' :
           priority === 'medium' ? '中' :
           '低'}
        </Tag>
      ),
    },
    {
      title: '报告人',
      dataIndex: 'reporter',
      key: 'reporter',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: unknown, record: BugItem) => (
        <Button type="link" onClick={() => handleEdit(record)}>
          编辑
        </Button>
      ),
    },
  ];

  const fetchData = async (params: BugQueryParams) => {
    setLoading(true);
    try {
      const response = await bugServer.getBugList(params);
      setData(response.list);
      setTotal(response.total);
    } catch (err) {
      message.error('获取数据失败');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const params: BugQueryParams = {
      pageSize,
      current,
      ...form.getFieldsValue(),
    };
    fetchData(params);
  }, [current, pageSize]);

  const handleSearch = () => {
    setCurrent(1);
    const params: BugQueryParams = {
      pageSize,
      current: 1,
      ...form.getFieldsValue(),
    };
    fetchData(params);
  };

  const handleReset = () => {
    form.resetFields();
    handleSearch();
  };

  const handleEdit = (bug: BugItem) => {
    setEditingBug(bug);
    setModalVisible(true);
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      if (editingBug) {
        await bugServer.updateBug(editingBug.id, values);
        message.success('更新成功');
      } else {
        await bugServer.createBug(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      handleSearch();
    } catch (err) {
      message.error('操作失败');
      console.error(err);
    }
  };

  const handleModalCancel = () => {
    setModalVisible(false);
    setEditingBug(null);
    form.resetFields();
  };

  return (
    <div className="bug-page">
      <Form
        form={form}
        layout="inline"
        className="search-form"
      >
        {searchFields.includes('title') && (
          <Form.Item name="title" label="标题">
            <Input placeholder="请输入标题" />
          </Form.Item>
        )}
        {searchFields.includes('status') && (
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态" style={{ width: 120 }}>
              <Option value="pending">待处理</Option>
              <Option value="processing">处理中</Option>
              <Option value="resolved">已解决</Option>
            </Select>
          </Form.Item>
        )}
        {searchFields.includes('priority') && (
          <Form.Item name="priority" label="优先级">
            <Select placeholder="请选择优先级" style={{ width: 120 }}>
              <Option value="high">高</Option>
              <Option value="medium">中</Option>
              <Option value="low">低</Option>
            </Select>
          </Form.Item>
        )}
        {searchFields.includes('reporter') && (
          <Form.Item name="reporter" label="报告人">
            <Input placeholder="请输入报告人" />
          </Form.Item>
        )}
        {searchFields.includes('createTime') && (
          <Form.Item name="createTime" label="创建时间">
            <RangePicker />
          </Form.Item>
        )}
        <div className="form-footer">
          <Button type="primary" onClick={handleSearch}>
            搜索
          </Button>
          <Button onClick={handleReset}>
            重置
          </Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => setModalVisible(true)}>
            新建
          </Button>
          <Button icon={<SettingOutlined />} onClick={() => setVisible(true)}>
            配置展示项
          </Button>
        </div>
      </Form>

      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        loading={loading}
        pagination={{
          total,
          current,
          pageSize,
          onChange: (page, size) => {
            setCurrent(page);
            setPageSize(size);
          },
        }}
      />

      <Modal
        title={editingBug ? '编辑Bug' : '新建Bug'}
        visible={modalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={editingBug || {}}
        >
          <Form.Item
            name="title"
            label="标题"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="description"
            label="描述"
            rules={[{ required: true, message: '请输入描述' }]}
          >
            <Input.TextArea rows={4} />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select>
              <Option value="pending">待处理</Option>
              <Option value="processing">处理中</Option>
              <Option value="resolved">已解决</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="priority"
            label="优先级"
            rules={[{ required: true, message: '请选择优先级' }]}
          >
            <Select>
              <Option value="high">高</Option>
              <Option value="medium">中</Option>
              <Option value="low">低</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="配置展示项"
        visible={visible}
        onOk={() => setVisible(false)}
        onCancel={() => setVisible(false)}
      >
        <Tree
          checkable
          checkedKeys={searchFields}
          onCheck={(checked: Key[] | { checked: Key[]; halfChecked: Key[] }) => {
            const checkedKeys = Array.isArray(checked) ? checked : checked.checked;
            setSearchFields(checkedKeys as string[]);
          }}
          treeData={[
            {
              title: '搜索项',
              key: 'search-fields',
              children: [
                { title: '标题', key: 'title' },
                { title: '状态', key: 'status' },
                { title: '优先级', key: 'priority' },
                { title: '报告人', key: 'reporter' },
                { title: '创建时间', key: 'createTime' },
              ],
            },
          ]}
        />
      </Modal>
    </div>
  );
}; 